package com.iweipan.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.iweipan.R;
import com.iweipan.adapter.OrderListAdapter;
import com.iweipan.base.WPBaseFragment;
import com.iweipan.bean.OrderListBean;
import com.iweipan.utils.sputils.SPUtils;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import okhttp3.Call;

import static com.iweipan.base.WPUrlBase.WP_ORDER_LIST;

/**
 * Created by Administrator on 2016/11/17.
 */

public class TwoFragment extends WPBaseFragment implements RadioGroup.OnCheckedChangeListener {


    @BindView(R.id.create_order)
    RadioButton createOrder;
    @BindView(R.id.out_order)
    RadioButton outOrder;
    @BindView(R.id.order_radioGroup)
    RadioGroup orderRadioGroup;
    @BindView(R.id.order_listView)
    ListView orderListView;
    @BindView(R.id.error)
    TextView error;
    @BindView(R.id.twinklingRefreshLayout)
    TwinklingRefreshLayout twinklingRefreshLayout;
    private String wp_token;
    int pageSize = 0;
    boolean isFistPager = true;
    private OrderListAdapter orderListAdapter;
    private ArrayList<OrderListBean.ResultBean> resultBeanArrayList;
    private ArrayList<OrderListBean.ResultBean> outResultBeanArrayList;

    public static TwoFragment newInstance() {

        Bundle args = new Bundle();

        TwoFragment fragment = new TwoFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void initData() {

        resultBeanArrayList = new ArrayList<OrderListBean.ResultBean>();
        outResultBeanArrayList = new ArrayList<OrderListBean.ResultBean>();
        orderRadioGroup.setOnCheckedChangeListener(this);
        orderListAdapter = new OrderListAdapter(mActivity);
        orderListView.setEmptyView(error);
        orderListView.setAdapter(orderListAdapter);
        wp_token = (String) SPUtils.get(mActivity, "wp_token", "空");
        if (!wp_token.equals("空")) {
            initHttpData(true);
        }
        twinklingRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                initHttpData(true);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                initHttpData(false);
            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        wp_token = (String) SPUtils.get(mActivity, "wp_token", "空");
        if (!wp_token.equals("空")) {
            initHttpData(true);
        }
    }

    private void initHttpData(final boolean toRefresh) {

        if (toRefresh) {
            pageSize = 0;
        }
        pageSize += 50;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("token", wp_token);
            jsonObject.put("type", "all");
            jsonObject.put("pageNo", "0");
            jsonObject.put("pageSize", pageSize);
            OkHttpUtils.get()
                    .url(WP_ORDER_LIST)
                    .addParams("p", jsonObject.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
//                            Log.e("TwoFragment", response);
                            try {
                                JSONObject jsonObject1 = new JSONObject(response);
                                JSONArray result = jsonObject1.getJSONArray("result");
                                if (result != null && result.length() > 0) {
                                    resultBeanArrayList.clear();
                                    outResultBeanArrayList.clear();
                                    for (int i = 0; i < result.length(); i++) {
                                        JSONObject order = result.getJSONObject(i);
                                        int reType = order.getInt("reType");
                                        if (reType == 1) {
                                            //建仓
                                            OrderListBean.ResultBean creatData = new OrderListBean.ResultBean();
                                            creatData.setProDesc(order.getString("proDesc"));
                                            creatData.setWeight(order.getDouble("weight"));
                                            creatData.setReType(order.getInt("reType"));
                                            creatData.setSpec(order.getString("spec"));
                                            creatData.setCouponFlag(order.getInt("couponFlag"));
                                            if (order.getInt("couponFlag") == 0) {
                                                creatData.setFee(order.getDouble("fee"));
                                            } else {
                                                creatData.setFee(0);
                                            }
                                            creatData.setAddTime(order.getString("addTime"));
                                            creatData.setBuyDirection(order.getInt("buyDirection"));
                                            creatData.setBuyPrice(order.getInt("buyPrice"));
                                            creatData.setBuyMoney(order.getInt("buyMoney"));
                                            resultBeanArrayList.add(creatData);
                                        } else if (reType == 2) {
                                            OrderListBean.ResultBean outData = new OrderListBean.ResultBean();
                                            outData.setProDesc(order.getString("proDesc"));
                                            outData.setWeight(order.getDouble("weight"));
                                            outData.setSpec(order.getString("spec"));
                                            outData.setReType(order.getInt("reType"));
                                            outData.setCouponFlag(order.getInt("couponFlag"));
                                            outData.setBuyDirection(order.getInt("buyDirection"));
                                            outData.setBuyMoney(order.getInt("buyMoney"));
                                            if (order.getInt("couponFlag") == 0) {
                                                outData.setFee(order.getDouble("fee"));
                                            } else {
                                                outData.setFee(0);
                                            }
                                            outData.setSellPrice(order.getInt("sellPrice"));
                                            outData.setSellTime(order.getString("sellTime"));
                                            outData.setOrderType(order.getInt("orderType"));
                                            outData.setPlAmount(order.getDouble("plAmount"));
                                            outResultBeanArrayList.add(outData);
                                        }
                                    }
                                    if (toRefresh) {
                                        twinklingRefreshLayout.finishRefreshing();
                                    } else {
                                        twinklingRefreshLayout.finishLoadmore();
                                    }
                                    if (isFistPager) {
                                        orderListAdapter.setData(resultBeanArrayList);
                                    } else {
                                        orderListAdapter.setData(outResultBeanArrayList);
                                    }
//                                    if (resultBeanArrayList != null && resultBeanArrayList.size() > 0) {

//                                    }

                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();

        }


    }

    @Override
    public void initDestrory() {

    }

    @Override
    public void initView() {
    }

    @Override
    public View inflaterView(LayoutInflater inflater, ViewGroup container) {
        return inflater.inflate(R.layout.fragment_two, null);
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.out_order:
                isFistPager = false;
                orderListAdapter.setData(outResultBeanArrayList);
                break;
            case R.id.create_order:
                isFistPager = true;
                orderListAdapter.setData(resultBeanArrayList);
                break;
        }
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    setGoToTwo();
                    break;
            }
            return false;
        }
    });


    public void setGoToTwo() {
        if (outOrder != null) {
            outOrder.setChecked(true);
        } else {
            handler.sendEmptyMessage(0);
        }

    }


}
